/*
 * comlan
 */

package com.comlan.installer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class CheckApkReceiver extends BroadcastReceiver {
	public static final String APK_PACKAGE_NAME_MTERM = "com.comlan.mterm";
	public static final String APK_PACKAGE_NAME_TMSCLIENT = "com.comlan.mterm.tms";
	public static final String APK_PATH = "data/data/com.comlan.mterm.tms/files/";
	public static final String APK_INDEX_PATH = "data/data/com.comlan.mterm.tms/files/index.txt";
	private static final String INSTALL_SERVICE_ACTION = "com.comlan.installer";
	private static final String UNINSTALL_SERVICE_ACTION = "com.comlan.uninstaller";
	private static final String TAG = "installer";
	private Timer timer = new Timer();
	@Override
	public void onReceive(Context context, Intent intent) {
		//if(timer != null) timer.cancel();
		final Context ctx = context;
		Log.d("test", "CheckApkReceiver onReceive");
		
//		ContentResolver cr = context.getContentResolver();
//		ContentValues values = new ContentValues();
//		values.put("pdp_watchdog_max_pdp_reset_fail_count", 1000);
//		Uri url = Settings.Secure.CONTENT_URI;
//		cr.insert(url, values );
//		
//		Log.d("test", "insert to pdp_watchdog_max_pdp_reset_fail_count 1000");
		
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				Log.d("test", "start timer");
				if(!isPkgInstalled(ctx, APK_PACKAGE_NAME_MTERM)){
					//install
					Log.d("test", "update install mterm" );
					updateInstall(ctx, APK_PACKAGE_NAME_MTERM);
				}
//				else{
//					//check if isn't install success
//					Log.d("test", "check if isn't install success");
//					if(!isInstallSucceed(ctx,APK_PACKAGE_NAME_MTERM)){
//						//copy and fresh install
//						Log.d("test", "copy and fresh install");
//						freshInstall(ctx, APK_PACKAGE_NAME_MTERM);
//					}else{						
//						Log.d("test", "install succeed");
//					}
//				}
				if(!isPkgInstalled(ctx, APK_PACKAGE_NAME_TMSCLIENT)){
					//install
					Log.d("test", "update install tms" );
					updateInstall(ctx, APK_PACKAGE_NAME_TMSCLIENT);
				}
			}
		},1000 * 30 );
		
	} 
	
	public static void freshInstall(Context context, String packageName){
		File file = new File(APK_PATH);
		if(file == null) return;
		File[] files = file.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String filename) {
				if(filename.endsWith(".apk")){
					return true;
				}
				return false;
			}
		});
		String path;
		if(files == null || files.length == 0) return;
		for(int i= 0; i < files.length; i++){
			path = files[i].getPath();
			Log.d("test", "freshInstall path = " + path);
			String pkgName = getPackageName(context, path);
			if(packageName.equals(pkgName)){
				//copy 
				
				//uninstall
				Intent uninstallIntnet = new Intent(UNINSTALL_SERVICE_ACTION);
				uninstallIntnet.putExtra("packageName", packageName);
				context.startService(uninstallIntnet);
				try {
					Thread.sleep(1000*10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				//install
				Intent intent = new Intent(INSTALL_SERVICE_ACTION);
				intent.putExtra("id", -1);
				intent.putExtra("path", APK_PATH + files[i].getName());
				context.startService(intent);
				break;
			}
		}
	}
	
	public static void updateInstall(Context context, String packageName){
		try{
			//check file 
			File file = new File(APK_INDEX_PATH);
			if(file == null) return;
			FileInputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			StringBuffer sb = new StringBuffer();
			while((len = fis.read(buffer))!=-1){
				sb.append(new String(buffer,0,len));
			}
			String fileInfos = sb.toString();
			//get file name list
			String[] files = fileInfos.split("@@");
			if(files == null || files.length == 0) return;
			String path;
			for(int i= 0; i < files.length; i++){
				if(files[i].trim().length() == 0) continue;
				path = APK_PATH + files[i];
				Log.d("test", "updateInstall path = " + path);
				String pkgName = getPackageName(context, path);
				if(packageName.equals(pkgName)){
					Intent intent = new Intent(INSTALL_SERVICE_ACTION);
					intent.putExtra("id", -100);
					intent.putExtra("path", path);
					context.startService(intent);
					Log.d("test", "updateInstall startService = " + path);
					break;
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getPackageName(Context context, String path) {
		try{
			PackageManager pm = context.getPackageManager();
			PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
			if (info != null) {
				ApplicationInfo appInfo = info.applicationInfo;
				String packageName = appInfo.packageName;
				return packageName;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	private static boolean isPkgInstalled(Context ctx, String packageName){
        PackageManager pm = ctx.getPackageManager();
        try {
            pm.getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {
            return false;
        }
        return true;
    }
	public static boolean isInstallSucceed(Context context,String packageName){
		boolean testSucceeded;
		Context ctx = null;
		try {
			ctx = context.createPackageContext(packageName, Context.CONTEXT_IGNORE_SECURITY);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		File filesDir = ctx.getFilesDir();
		if (filesDir == null) {
			testSucceeded = false;
		}
		else {
			try {
				File testFile = File.createTempFile("udp", "check", filesDir);
				testSucceeded = testFile.canWrite();
				testFile.delete();
			} catch (IOException e) {
				testSucceeded = false;
			}			
		} 
		return testSucceeded;  
	} 
	
}
 